/* eslint-disable prettier/prettier */
/* eslint-disable react-native/no-inline-styles */
import React, { useEffect, useState } from 'react';
import { DeviceEventEmitter,View, Image, StyleSheet, Text,TextInput, KeyboardAvoidingView,TouchableOpacity ,Modal, ToastAndroid, ScrollView} from 'react-native';
import styles from './DialogStyles';
import CheckBox from '@react-native-community/checkbox';
import { API_BASE,API_PARAMS,API_PAY } from '../../enums/api';
import { DecodeToken, updateToken } from '../../services/DecodeToken';
import { RootSiblingPortal } from 'react-native-root-siblings';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getBuy } from '../../services/DecodeToken';
import { NativeModules } from 'react-native';
import MD5 from 'react-native-md5';
import { WXstate } from '../../enums/constant';
import {NetworkInfo} from 'react-native-network-info';
const {  WeChat } = NativeModules;
var timer = setInterval;
const url = API_BASE.TEST_URL + API_PAY.CREAT_ORDER;
const BUYLIST = [
  { title: '一至四年级上下全册' , value: 'purchase_all' },
  { title: '一年级上册', value: 'purchase_oneup' },
  { title: '一年级下册', value: 'purchase_onedown' },
  { title: '二年级上册', value: 'purchase_twoup' },
  { title: '二年级下册', value: 'purchase_twodown' },
  { title: '三年级上册', value: 'purchase_threeup' },
  { title: '三年级下册', value: 'purchase_threedown' },
  { title: '四年级上册', value: 'purchase_fourup' },
  { title: '四年级下册', value: 'purchase_fourdown' },

];
const Buybookpage = ({ success,visible,onClose,navigation}) => {
  const [phone, setPhone] = useState('');
  const [passwordcode, setPasswordcode] = useState('');
  const [agree,setAgree] = useState(false);
  const [brought,setBrought] = useState([]);
  const buybook = async (item)=>{
    WeChat.registerApp('wx89a522ad1639e6bd', '', (error, result) => {
      if (error) {
          console.error('注册失败:', error);
      } else {
          console.log('注册成功:', result);
      }
  });
  const BuyRequest = {
    apppackage: 'com.lzt.Chaizi',
    price : 1,
  };
  BuyRequest.productid = item;
  BuyRequest.productdetail = item;

  console.log('fetch ');

  try {
  await  NetworkInfo.getIPV4Address().then(ipAddress => {
      // console.log("ip");
      console.log(ipAddress);
      BuyRequest.clientip = ipAddress;
    });
  } catch (error) {
    console.log(error);
  }

   //============================向接口发送网络请求
   var rtoken = await AsyncStorage.getItem('rtoken');
   console.log('rtoken: ' + rtoken.toString());
   console.log('BuyRequest: ' +  JSON.stringify(BuyRequest) );
   fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'token': rtoken.toString(),
    },
    body: JSON.stringify(BuyRequest), // 直接使用对象
})
.then((response) => {
    // 检查响应是否正常（状态码200-299）
    if (!response.ok) {
        throw new Error('网络响应错误: ' + response.status);
    }
    return response.json();
})
.then((data) => {
    console.log('Response:', data);
    // 处理返回的数据
    if (data.msg === 'success') {
        // 登录成功
        var buyq  = data.data;
        console.log(buyq);
        Promise.all(
          WeChat.pay(buyq,(res) => {
          console.log('支付结果:', res);
        }));
    } else {
        // 登录失败
        alert('获取订单失败: ' + data.msg);
        onClose;
    }
})
.catch((error) => {
    console.error('Error:', error);
    alert('请求失败');
});
  };

  const initifo = async() => {
    let haveBroughTitmArray  = getBuy();
    return haveBroughTitmArray;
  };

  const updatelogin = async ( ) => {
      // 创建一个包含登录信息的JavaScript对象
       const loginInfo = await getInfoAsyncStorage(); // 等待异步获取登录信息
       if(loginInfo.passwordcode === null)
       { 
        setBrought([]);clearImmediate(timer);
        alert('更新数据失败，请登陆 ');}
    console.log(loginInfo);
      let url = '';
      // 构造URL
      url = API_BASE.TEST_URL + API_PARAMS.LOGIN;
  console.log(url);
      console.log('要更新数据');
        console.log(loginInfo);
        fetch(url, {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json',
          },
          body: JSON.stringify(loginInfo), // 直接使用对象
      })
        .then((response) => {
            // 检查响应是否正常（状态码200-299）
            if (!response.ok) {
                throw new Error('网络响应错误: ' + response.status);
            }
            return response.json();
        })
        .then((data) => {
            console.log('Response:', data);
            // 处理返回的数据
            if (data.msg === 'success') {
                // 登录成功
                  updateToken(data).then( br => { // 获取按钮
                    setBrought(br);
                    console.log(brought);
                  }); 
            } else {
                // 登录失败 
                return false; 
            }
        })
        .catch((error) => {
            console.error('Error:', error);
            alert('请求失败');
        });
  };

  const getInfoAsyncStorage = async () => {
    try {
      const passwordcode = await AsyncStorage.getItem('passwordcode');
      const phone = await AsyncStorage.getItem('phone');
      return { passwordcode, phone }; // 返回一个对象，包含 passwordcode 和 phone
    } catch (error) {
      // 处理错误
      console.error('AsyncStorage error: ', error);
      throw error; // 抛出错误，以便在外层捕获
    }
  };

useEffect(()=>{

    initifo().then(br => { // 获取按钮
          setBrought(br);
          console.log(brought);});

},[]);

  useEffect(() => {
      if (visible)
      {
          timer = setInterval(() => {
            if(!updatelogin()){
                clearImmediate(timer);
                alert('更新数据失败，请尝试重新登陆 ');
                onClose;
            }
          console.log('轮询');
       }, 1000);
      } else {
        if (timer){
          clearInterval(timer);
        }
      }
  },[visible]);

  //获取当前登录状态下，所持有的密码和账号
  if (!visible) {return null;}
  return (

<Modal
    animationType="slide"
    transparent={true}
    visible={visible}
    onRequestClose={onClose}
    style={styles.dialogContainer}>
      <TouchableOpacity style={{flex:1,position:'absolute'}} />
         <View style={styles.dialogContainer}>

            <View style={{backgroundColor:'#e8f1f8',height:'60%',width:'70%',borderRadius:20}}>
                <Text style={{textAlign:'center',top:'5%',fontWeight:'bold',fontSize:40,color:'#2bbceb'}}>欢迎选购</Text>
               <View>
               <ScrollView style={{top:'20%',height:'70%' }}  contentContainerStyle={{ flexGrow: 1 }}>
                {BUYLIST.map((item) => (
                  <View key={item.value} style={{flexDirection: 'row',height:120}}>
                      <Image source={ {uri: `${'asset:/purchase/' + item.value + '.png'}`}} style={{width:'30%',height:'auto',margin:4}} />

                        <View style={{width:'60%', alignItems:'flex-end'}}>

                            <Text style={{fontSize:25,color:'black',fontWeight:'bold',margin:0,width:'30'}}>{item.title}</Text>
                            {!brought.includes(item.title) ? <TouchableOpacity
                              key={item.value}
                              style={styles.buttonbuy}
                              onPress={()=>buybook(item.title)}>
                                <Text style={styles.tb}>购买</Text>
                            </TouchableOpacity> : <TouchableOpacity
                              key={item.value}
                              style={styles.buttonbuy}
                              onPress={()=>{}}>
                                <Text style={styles.tb}>已购买</Text>
                            </TouchableOpacity>}

                        </View>
                  </View>
                ))}
                <View style={{top:'20%',height:'400%' }} />
                </ScrollView>
               </View>

            </View>
         </View>

</Modal>


    );

};



export default Buybookpage;
